package com.jinliang.blogweb.controller;

import com.jinliang.blogweb.entity.File;
import com.jinliang.blogweb.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@RequestMapping(value = "file")
public class FileController {

    private final FileMapper fileMapper;

    public FileController(FileMapper fileMapper) {
        this.fileMapper = fileMapper;
    }

    @GetMapping(value = "/file")
    public void getFile(@RequestParam("id") String id, HttpServletResponse response) throws IOException {
        File file = fileMapper.selectById(id);
        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(file.getValue());
        outputStream.flush();
        outputStream.close();
    }


    @PostMapping(value = "/fileUpload")
    public File fileUpload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (file.isEmpty()) {
            System.out.println("文件为空空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        InputStream ins = file.getInputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = ins.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.flush();
        File images = new File();
        images.setName(fileName);
        images.setValue(bos.toByteArray());
        images.setId(UUID.randomUUID().toString());
        fileMapper.insert(images);
        return images;
    }
}
